package com.lagou.edu.service.impl;

import com.lagou.edu.dao.UserDao;
import com.lagou.edu.pojo.LagouToken;
import com.lagou.edu.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.UUID;


@Service
public class UserServiceImpl implements IUserService {


    @Autowired
    private UserDao userDao;

    @Override
    public boolean register(String email, String password, String code) {
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        lagouToken.setPassword(password);
        lagouToken.setToken(UUID.randomUUID().toString());
        LagouToken result = userDao.saveAndFlush(lagouToken);
        if(result != null){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public boolean checkRegister(String email) {
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        Example<LagouToken> example = Example.of(lagouToken);
        Optional<LagouToken> one = userDao.findOne(example);
        if(one.isEmpty()){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public LagouToken login(String email, String password) {
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        lagouToken.setPassword(password);
        Example<LagouToken> example = Example.of(lagouToken);
        Optional<LagouToken> one = userDao.findOne(example);
        if(one.isEmpty()){
            return null;
        }else{
            LagouToken result = one.get();
            return result;
        }

    }

    @Override
    public String info(String token) {
        LagouToken lagouToken = new LagouToken();
        lagouToken.setToken(token);
        Example<LagouToken> example = Example.of(lagouToken);
        Optional<LagouToken> one = userDao.findOne(example);
        if(one.isEmpty()){
            return null;
        }else {
            LagouToken result = one.get();
            return result.getEmail();
        }
    }

    @Override
    public void createToken(LagouToken token) {
        userDao.updateToken(token.getEmail(),token.getToken());
    }
}
